# - Coding UTF8 -
#
# Networked Decision Making
# Site: http://code.google.com/p/global-decision-making-system/
#
# License Code: GPL, General Public License v. 2.0
# License Content: Creative Commons Attribution 3.0
#
# Also visit: www.web2py.com
#             or Groups: http://groups.google.com/group/web2py 
# 	For details on the web framework used for this development
#
# Developed by Russ King (newglobalstrategy@gmail.com
# Russ also blogs occasionally at proudofyourplanent.blogspot.com
# His general thinking on why this project is very important is availalbe at
# http://www.scribd.com/doc/98216626/New-Global-Strategy
#
# This controller handles submission of questiosn and confirmation that the 
# question has been submitted
#########################################################################
## This scaffolding model makes your app work on Google App Engine too
## File is released under public domain and you can use without limitations
#########################################################################

#for testing remove later
from gluon.custom_import import track_changes; track_changes(True)

if not request.env.web2py_runtime_gae:
    ## if NOT running on Google App Engine use SQLite or other DB
    db = DAL('sqlite://storage.sqlite')    
else:
    #test from gluon.contrib.gae_memcache import MemcacheClient
    #test from gluon.contrib.memdb import MEMDB
    #test cache.memcache = MemcacheClient(request)
    #test cache.ram = cache.disk = cache.memcache
    ## connect to Google BigTable (optional 'google:datastore://namespace')
    #db = DAL('google:datastore')
    #test db = DAL('gae')
    ## store sessions and tickets there
    ## session.connect(request, response, db = db)
    ## or store session in Memcache, Redis, etc.
    #from gluon.contrib.memdb import MEMDB
    #test from google.appengine.api.memcache import Client
    #test session.connect(request, response, db = MEMDB(Client()))



    #Below from 261 welcome app
    ## connect to Google BigTable (optional 'google:datastore://namespace')
    db = DAL('google:datastore')
    ## store sessions and tickets there
    # session.connect(request, response, db=db)
    ## or store session in Memcache, Redis, etc.
    from gluon.contrib.memdb import MEMDB
    from google.appengine.api.memcache import Client
    session.connect(request, response, db = MEMDB(Client()))


## by default give a view/generic.extension to all actions from localhost
## none otherwise. a pattern can be 'controller/function.extension'
response.generic_patterns = ['*'] if request.is_local else []
## (optional) optimize handling of static files
# response.optimize_css = 'concat,minify,inline'
# response.optimize_js = 'concat,minify,inline'

#########################################################################
## Here is sample code if you need for
## - email capabilities
## - authentication (registration, login, logout, ... )
## - authorization (role based authorization)
## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss)
## - old style crud actions
## (more options discussed in gluon/tools.py)
#########################################################################

import os
from gluon.tools import Auth, Crud, Service, PluginManager, prettydate, Mail
auth = Auth(db, hmac_key=Auth.get_or_create_key())
crud, service, plugins = Crud(db), Service(), PluginManager()

#all other tables in db_gdms.py but this needs to be defined before
#extra fields in auth
db.define_table('category',
Field('cat_desc','string',label='Category'),
Field('categorydesc','text',label='Description'),
format='%(cat_desc)s')

db.define_table('continent',
Field('continent_name','string',label='Continent'),
format='%(continent_name)s')

db.define_table('country',
Field('country_name','string',label='Country'),
Field('continent','string', label='Continent'),
Field('isg20','boolean',label='G20 Member', default=False),
Field('leader','string', label='Leader'),
Field('email','string', label='Leader E-mail'),
Field('website','string',label='Leader website'),
Field('contact_method','string',requires=IS_IN_SET(['email','website']),
       default='email',label='Contact Method'),
format='%(country_name)s')

#changed to derelationalise country to subdivision for GAE
#now ajax query should return valid subdivisions on change of country but
#default should just be Unspecified
db.define_table('subdivision',
Field('subdiv_name','string',label='Sub-Division eg State, Province, County'),
Field('country','string'),
format='%(subdiv_name)s')

db.define_table('scope',
Field('description','string'),
format='%(description)s')

# coding: utf8 
db.define_table('config',
Field('reqapproval','boolean',default=False, label='Require approval of new users'),
Field('reqverification','boolean',default=False, label='Require verification of new users'))

#Not sure any of this is now needed lets try and remove and see what happens

if session.init is None:
    #ensure minimum default values are in place to allow rest of the model to be created
    if db(db.config.id > 0).isempty():
        db.config.insert()
    if db(db.scope.id > 0).isempty():
        db.scope.insert(description="1 Global")
    if db(db.continent.id > 0).isempty():
        db.continent.insert(continent_name="Unspecified")
    if db(db.category.id > 0).isempty():
        db.category.insert(cat_desc="None",
                             categorydesc = "Set to select all questions")
        db.category.insert(cat_desc="Unspecified",
                             categorydesc = "Catchall category")

    # confirm config table and then retrieve settings
    # will retrieve global settings here as well I think
    verification = db(db.config.id>0).select(db.config.reqverification).first().reqverification
    if verification is None:
        session.verification = False
    else:
        session.verification = verification    
    approval = db(db.config.id>0).select(db.config.reqapproval).first().reqapproval
    if approval is None:
        session.approval = False
    else:
        session.approval = approval
    
    session.init = True
    db.commit()
    

auth.settings.extra_fields['auth_user'] = [
Field('numquestions','integer', default = 0, readable=False, writable=False, label='Answered'),
Field('score','integer',  default = 0, readable=False, writable=False, label='Score'),
Field('rating','integer',  default = 0, readable=False, writable=False, label='Rating'),
Field('level','integer',  default = 1, readable=False, writable=False, label='Level'),
Field('numcorrect','integer',  default = 0, readable=False, writable=False, label = 'Correct'),
Field('numwrong','integer',  default = 0, readable=False, writable=False, label='Wrong'),
Field('numpassed','integer',  default = 0, readable=False, writable=False, label='Passed'),
Field('exclude_categories', 'list:string',default = 'None', label='Excluded Categories',
      comment="Select subjects you don't want questions on"),
Field('continent', 'string', default = 'Unspecified', label='Continent'),
Field('country', 'string', default ='Unspecified',label='Country'), 
Field('subdivision', 'string', default ='Unspecified',label='Sub-division')]



## create all tables needed by auth if not custom tables
auth.define_tables(username=True)

#mgr = db(db.auth_group.role=='manager').select().first()
#if mgr is None:
#    auth.add_group('manager', 'The admin group for the app')


#auth.settings.manager_group_role = 'manager'
#below was previous suggestion and seems to be required for 260 again
auth.settings.auth_manager_role = 'manager'

#this could be using a lot of reads as well - may 
#db.auth_user.exclude_categories.requires = IS_IN_DB(db, 'category.cat_desc')
db.auth_user.exclude_categories.requires = IS_IN_DB(db, 'category.cat_desc', cache=(cache.ram,3600),multiple=True)
#db.auth_user.continent.requires = IS_IN_DB(db, 'continent.continent_name', cache=(cache.ram,3600))
db.auth_user.continent.requires = IS_IN_DB(db, 'continent.continent_name')

## configure email
mail=auth.settings.mailer
mail.settings.server = 'gae'
mail.settings.sender = 'newglobalstrategy@gmail.com'
##mail.settings.login = 'username:password'

filename='private/emaillogin.key'
path = os.path.join(request.folder, filename)

if os.path.exists(path):
    mail.settings.login = open(path, 'r').read().strip()


## configure auth policy
auth.settings.registration_requires_verification = session.verification
auth.settings.registration_requires_approval = session.approval
auth.settings.reset_password_requires_verification = True


## if you need to use OpenID, Facebook, MySpace, Twitter, Linkedin, etc.
## register with janrain.com, write your domain:api_key in private/janrain.key
## if you don't want to use then just dont setup a janrain.key file
## this works if key supplied - however not currently using as janrain doesn't 
## appear to work with ie10 - looks like python social auth will be the way to go
## here in due course
from gluon.contrib.login_methods.rpx_account import use_janrain
use_janrain(auth,filename='private/janrain.key')


#########################################################################
## Define your tables below (or better in another model file)
##
## >>>main tables are all defined in db_gdms.py
##
#########################################################################

